var bg = chrome.extension.getBackgroundPage();
var winId;//当前windowId
$(function(){	
	chrome.windows.getCurrent(function(win){
		winId = win.id;
		initPage();
		//手动按钮,不带延时
		$("#btnFill").bind('click',function(){
			syncInput();
			bg.timeOut=0;
			bg.runEachWin();
		});

		//自动按钮
		$("#setTime").bind('click',function(){
			syncInput();
			var timeOut = $('#timeOut').val();
			bg.timeOut = timeOut;
			var timeToSet = $('#timeInput').val();
			if(timeToSet){
				if(bg.timeSet != undefined && bg.timeSet != null){
					bg.changeTimer(timeToSet);
				}else{
					bg.setTimer(timeToSet);
				}
				$('#setTime').val('计时中');
			}else{
				alert('请设置时间！');
			}
		});
	});	
});

function syncInput(){
	var payType = $('input[name="payType"]:checked').val();
	var grouponId = $('#grouponId').val();
	var orderCode = $('#orderCode').val();
	var addrId = $('#addrId').val();
	bg.setPayType(winId,payType);
	bg.ruleType = $('input[name="ruleType"]:checked').val();
	bg.mAddCart[winId] = $('#productId').val();
	bg.grouponId[winId] = grouponId;
	bg.orderCode[winId] = orderCode;
	bg.addrId[winId] = addrId;
}

function initPage(){
	var timeSet = bg.timeSet;
	$('#timeInput').val(timeSet);
	$('#timeOut').val(bg.timeOut);
	$('#grouponId').val(bg.grouponId[winId]);
	$('#orderCode').val(bg.orderCode[winId]);
	$('#addrId').val(bg.addrId[winId]);
	// $('#myPhone').val(bg.myPhone[winId]);
	var oldPayType = bg.getPayType(winId);
	if((bg.ruleType==1 || oldPayType) && timeSet != undefined && timeSet != null){
		bg.console.log('timeSet is:' + timeSet);
		$('#setTime').val('计时中');
	}
	if($('input[name="payType"]:eq(1)').val()==oldPayType){
		$('input[name="payType"]:eq(1)').attr("checked",true);
	}else if($('input[name="payType"]:eq(2)').val()==oldPayType){
		$('input[name="payType"]:eq(2)').attr("checked",true);
	}else{//没有设置或者设置了第一种，默认就是扫码
		$('input[name="payType"]:eq(0)').attr("checked",true);
	}
	//价格类型
	if(bg.ruleType==7){
		$('#shanType').attr("checked",true);
	}else if(bg.ruleType==1){//换购
		$('#huangou').attr("checked",true);
		$("#huangouOptions").show();
		$("#miandanOptions").hide();
	}else{
		$('#tuanType').attr("checked",true);
	}
	var pid = bg.mAddCart[winId];
	if(pid != undefined && pid != ''){
		$('#autoAddCart').attr('checked','checked');
		$('#thingToAdd').toggle();
		$('#productId').val(pid);
	}
	$("#huangou").click(function(){
		$("#huangouOptions").show();
		$("#miandanOptions").hide();
	});
	$('#tuanType,#shanType').click(function(){
		$("#miandanOptions").show();
		$("#huangouOptions").hide();
	});
	//切换
	$('#autoAddCart').bind('click',function(){
		$('#thingToAdd').toggle();	
	});

	$('#grouponId,#orderCode,#addrId').blur(function(){
		syncInput();
	});
}